package com.bdqn.springbootno1.service.impl;


import com.bdqn.springbootno1.dao.AppCategoryDao;
import com.bdqn.springbootno1.entity.AppCategory;
import com.bdqn.springbootno1.service.AppCategoryService;
import com.bdqn.springbootno1.vo.CategoryTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryServiceImpl implements AppCategoryService {
    @Autowired
    private AppCategoryDao appCategoryDao;


    @Override
    public CategoryTreeVo list() {
        //把要的数据封装到该类中了
        List<CategoryTreeVo> voList = new ArrayList<>();

        List<AppCategory> appCategories = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : appCategories) {
            CategoryTreeVo categoryTreeVo = new CategoryTreeVo();
            BeanUtils.copyProperties(appCategory,categoryTreeVo);   //把多余的字段剔除掉
            voList.add(categoryTreeVo);
        }

        CategoryTreeVo tree = new CategoryTreeVo();
        for (CategoryTreeVo vo : voList) {
            if(vo.getParentId()==null){
                // 查一级分类
                tree = findChild(vo,voList);
            }
        }
        return tree;
    }

    private CategoryTreeVo findChild(CategoryTreeVo vo, List<CategoryTreeVo> voList) {
        vo.setCategoryTreeVoList(new ArrayList<>());
        for (CategoryTreeVo categoryTreeVo : voList) {
            if(vo.getId()==categoryTreeVo.getParentId()){
                 //装进去
                vo.getCategoryTreeVoList().add(categoryTreeVo);
                findChild(categoryTreeVo,voList);
            }
        }
        return vo;
    }
}
